package br.com.gentech.commons.model.dao.jpa;

import java.util.List;

import javax.persistence.EntityManager;

import br.com.gentech.commons.model.dao.CrudDAO;
import br.com.gentech.commons.model.dao.DAOException;
import br.com.gentech.commons.model.entity.IdentifiableEntity;


/**
 * Implementação base para um DAO que disponibiliza as operações CRUD de persistência em banco de dados relacionais.
 * 
 * @author AC de Souza
 *
 */
public abstract class JpaBaseDAO<T extends IdentifiableEntity<K>, K> implements CrudDAO<T, K>{
	protected final EntityManager manager;

	public JpaBaseDAO(EntityManager manager) {
		this.manager = manager;
	}
	public abstract Class<T> getEntityClass();

	
	public T save(T unsaved) {
		try{
			if(unsaved.getOID() == null){
				manager.persist(unsaved);
			}else{
				manager.merge(unsaved);
			}
			
			return unsaved;
		}catch (RuntimeException e){
			throw new DAOException(e);
		}
	}

	public void remove(K id) {
		try{
			manager.remove( getReference(id) );
		}catch (RuntimeException e){
			throw new DAOException(e);
		}
	}
	
	protected T getReference(K id){
		return manager.getReference(getEntityClass(), id);
	}
	@SuppressWarnings("unchecked")
	public List<T> find(){
		return manager.createQuery("select e from "+ getEntityClass().getName() +" e").getResultList();
	}
	public T find(K id){
		return manager.find(getEntityClass(), id);
	}
}